package Sort_work;

import java.util.Arrays;

/**
 * 堆排序
 *
 */
public class Heap_Sort {
    //向下调整建立大根堆
    public static void siftDown(int[] array,int parent,int len) {
        int child = (2*parent)+1;
        while(child < len) {
            if(child+1 < len && array[child+1] > array[child]) {
                child++;
            }
            if(array[child] > array[parent]) {
                swap(array,child,parent);
                parent = child;
                child = (2*parent)+1;
            } else {
                break;
            }
        }

    }
    public static void swap(int[] array,int x,int y) {
        int tmp = array[x];
        array[x] = array[y];
        array[y] = tmp;
    }

    public static void creatBigheap(int[] array) {
        int parent = (array.length-1-1) / 2;
        for (int i = parent; i >= 0; i--) {
            siftDown(array,i, array.length);
        }
    }
    public static void heapSort(int[] array) {
        int end = array.length - 1;
        while(end > 0) {
            swap(array,0,end);
            siftDown(array,0,end-1);
            end--;
        }
    }
    public static void main(String[] args) {
        int[] arr = {1,3,5,7,9,2,4,6,8};

        //从小到大排序
        creatBigheap(arr);
        System.out.println(Arrays.toString(arr));
        heapSort(arr);
        System.out.println(Arrays.toString(arr));

    }
}
